<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule\LogsModule\PhpModule;

use Nette\Object;
use Nette\Environment;

use Celebrio\FileSystem\TextFile;
use Celebrio\FileSystem\SafeFile;
use Celebrio\FileSystem\FileNotFoundException;
use Celebrio\FileSystem\FileException;

use KernelModule\LogsModule\LogsException;

/**
 * Kernel PHP Error base class.
 *
 * @abstract
 * @author Pavel
 */
abstract class Base extends Object {
    
    /**
     * @var array contains the filenames of html pages (exception ??-??-?? ...)
     */
    protected $excFileNames;

    /**
     * The number of logs displayed at the page.
     * @var integer
     */
    protected $limit = 50;

    /**
     * The number of logs processed by one http request.
     * @var integer
     */
    protected $processLimit = 1000;
    
    protected $logDir;

    protected $dirty;
    protected $clean;
    protected $count;
    protected $work;
    protected $hash;

    private $dirtyLogPath;
    private $cleanLogPath;
    private $countLogPath;
    private $hashLogPath;
    protected $workLogPath;




    public function __construct() {
        $this->logDir = Environment::expand('%logDir%'); // gets logDir value (../app/log implicit)

        $this->dirtyLogPath = $this->makePath('%logPHPErr%');
        $this->cleanLogPath = $this->makePath('%logPHPClean%');
        $this->countLogPath = $this->makePath('%logPHPCount%');
        $this->workLogPath = $this->makePath('%logPHPWork%');
        $this->hashLogPath = $this->makePath('%logPHPHash%');
        //parent::__construct();
    }

    /**
     * Transforms the file name into the full file path
     *
     * @param string file name
     * @return string absolute path to the file
     */
    private function makePath($fileAlias) {
        return $this->logDir . DIRECTORY_SEPARATOR . Environment::expand($fileAlias);
    }


    /**
     * Initializes the file, it means assigning the file handler to the class
     * variable.
     *
     * @param string determines which file will be initialized
     * @return boolean TRUE on success, FALSE when the error occures while
     * initializing the file handler
     * @throws Exception when the given parametr doesn't match any of the patterns
     */
    public function initializeLogFile($which) {
        try {
            switch ($which) {
                case "clean" :
                    if ($this->clean == NULL) {
                        $this->clean = new TextFile($this->cleanLogPath, "a+");
                    }
                    break;
                case "count" :
                    if ($this->count == NULL) {
                        $this->count = new TextFile($this->countLogPath, "a+");
                    }
                    break;
                case "dirty" :
                    if ($this->dirty == NULL) {
                        $this->dirty = new TextFile($this->dirtyLogPath, "r");
                    }
                    break;
                case "work" :
                    if ($this->work == NULL) {
                        $this->work = new TextFile($this->workLogPath, "r");
                    }
                    break;
                case "hash" :
                    if ($this->hash == NULL) {
                        $this->hash = new TextFile($this->hashLogPath, "a+");
                    }
                    break;
                default : 
                    throw new LogsInitializeException(_("No file selected. This should never happen."));
            }
            return TRUE;
        } catch (FileException $e) {
            return FALSE;
        }
    }

    /**
     * Returns the limit, it means amount of lines processed during 1 http request
     *
     * @return int limit
     */
    public function getLimit() {
        return $this->limit;
    }


    /**
     * Sets the global variable excFileNames. It contains the array of the filenames
     * with bluescreens of Nette now.
     */
    public function setExcFileNames() {
        $this->excFileNames = $this->scanForMatch("exception");
    }


    /**
     * scanForMatch($match) browses the directory specified by the path in the class
     * variable logDir and returns the array of the files which match
     * (contain) the $match string
     *
     * @param string $match is the string we need in the filenames
     * @return array of the filenames
     */
    private function scanForMatch($match) {
        $fileNameArray = scandir($this->logDir);
        $retFileNameArray = array();
        foreach ($fileNameArray as $fileName) {
            if (preg_match("/".$match."/", $fileName)) {
                $retFileNameArray[] = $fileName;
            }
        }
        return $retFileNameArray;
    }


    /**
     * Extracts the datetime from the line and returns its timestamp
     *
     * @param string $line whole line from the log_file
     * @return timestamp of the log event
     */
    public function retrieveDate($line) {
        $logTimeStr = substr($line, 1, 20); //cuts out the datetime (string formated)
        $timestamp = strtotime($logTimeStr); //get timestamp from the log header
        return  $timestamp;
    }

    /**
     * Converts the timestamp to the log-formated string date
     *
     * @param integer $timestamp timestamp we want to convert
     * @return string datetime formated in the log-format
     */
    public function timestampToLogDate($timestamp) {
        return date('Y-m-d H-i-s', $timestamp); //get datetime in "log file" format
    }

}